import { Component, Vue, PropSync, Watch } from 'vue-property-decorator'
import AddressSelect from '@/components/addressSelect'
import Style from './style.less'
import { ElForm } from 'element-ui/types/form'
import service from '@/lib/service'

interface SyncData {
  id: number
  consigneeName: string
  consigneeMobile: string
  telephoneAreaCode: string
  consigneeTelephone: string
  provinceName: string // eg: "天津市"
  cityName: string // eg: "市辖区"
  areaName: string // eg: "和平区"
  fullCode: string // eg: "120000-120100-120101"
  areaDetail: string
  postcode: string // eg: '123456'
  defaultStatus: number // 0 不是默认 1是默认
}

/**
 * 使用方法：
  <AddressLayer 
    show={this.addressShow}
    {...{on: {
      'update:show': (val: boolean) => this.addressShow= val,
      'update:data': (val: any) => this.addressData = val
    }}}
    data={this.addressData}
    onSuccess={this.addressSuccess}
  />
 */
@Component({})
export default class AddressLayer extends Vue {
  // 控制显隐
  @PropSync('show', {}) private syncShow!: boolean
  // 控制修改数据
  @PropSync('data', {}) private syncData!: SyncData

  private title: string = '新增收货地址'
  private formData: any = {
    consigneeArea: '', // 用于判断地址是否填写
    cityName: '',
    areaName: '',
    provinceName: '',
    fullCode: '',
    areaDetail: '',
    postcode: '',
    consigneeName: '',
    consigneeMobile: '',
    telephoneAreaCode: '',
    consigneeTelephone: '',
    fixedTelephone: '', // 用于判断固定电话是否正确
    defaultStatus: false,
  }
  private loading: boolean = false
  private addressData: any = {
    province: '',
    city: '',
    area: '',
  }
  private hideDefaultStatus: boolean = false
  private formRules = {
    consigneeArea: [
      {
        required: true,
        message: '地址信息不能为空',
        trigger: 'change',
      },
    ],
    areaDetail: [
      {
        max: 255,
        min: 0,
        message: `长度应在 0 到 255 之间`,
        trigger: 'change',
      },
      {
        required: true,
        message: `详细地址不能为空`,
        trigger: 'change',
      },
    ],
    consigneeName: [
      {
        max: 20,
        min: 0,
        message: `长度不正确`,
      },
      {
        required: true,
        message: `收货人姓名不能为空`,
        trigger: 'change',
      },
    ],
    consigneeMobile: [
      {
        len: 11,
        message: '手机号格式不正确',
        trigger: 'change',
      },
      {
        required: true,
        message: `手机号码不能为空`,
        trigger: 'change',
      },
      {
        validator: (rule: any, value: any, cb: Function) => {
          if (!Number.isInteger(Number(value))) {
            cb(new Error('请输入数字'))
          } else {
            if (!value.startsWith('1')) {
              cb(new Error('手机号格式不正确'))
            }
          }
          cb()
        },
        trigger: 'change',
      },
    ],
    fixedTelephone: [
      {
        validator: (rule: any, value: any, cb: Function) => {
          const [area, phone] = value.split('-')

          if (value.length > 1) {
            if (
              !Number.isInteger(Number(area)) ||
              !Number.isInteger(Number(phone))
            ) {
              cb(new Error('请输入数字'))
            }
          }
          cb()
        },
        trigger: 'change',
      },
    ],
    postcode: [
      {
        validator: (rule: any, value: any, cb: Function) => {
          if (!Number.isInteger(Number(value))) {
            cb(new Error('请输入数字'))
          }
          cb()
        },
        trigger: 'change',
      },
      {
        len: 6,
        trigger: 'change',
        message: '长度不正确',
      },
    ],
  }

  protected render() {
    return (
      <el-dialog
        title={this.title}
        visible={this.syncShow}
        close-on-click-modal={false}
        {...{
          on: {
            'update:visible': (val: boolean) => this.$emit('update:show', val),
          },
        }}
        class={Style.addressLayer}
        width="569px"
      >
        <el-form
          ref="form"
          {...{ props: { model: this.formData, rules: this.formRules } }}
          label-position="right"
          label-width="100px"
          size="mini"
        >
          <el-form-item label="地址信息" prop="consigneeArea">
            <AddressSelect
              province={this.addressData.province}
              city={this.addressData.city}
              area={this.addressData.area}
              provinceProps={{ placeholder: '请选择省市' }}
              cityProps={{ placeholder: '全部' }}
              areaProps={{ placeholder: '区、县' }}
              fullCodeSplit="-"
              {...{
                on: {
                  'update:province': (val: string) => {
                    this.addressData.province = val
                  },
                  'update:city': (val: string) => {
                    this.addressData.city = val
                  },
                  'update:area': (val: string) => {
                    this.addressData.area = val
                  },
                  change: (data: any) => {
                    this.formData.consigneeArea = data
                    this.formData.cityName = data.cityName
                    this.formData.areaName = data.areaName
                    this.formData.provinceName = data.provinceName
                    this.formData.fullCode = data.fullCode
                  },
                },
              }}
            />
          </el-form-item>
          <el-form-item label="详细地址" prop="areaDetail">
            <el-input size="mini" v-model={this.formData.areaDetail} />
          </el-form-item>
          <el-form-item label="邮政编码" prop="postcode">
            <el-input size="mini" v-model={this.formData.postcode} />
          </el-form-item>
          <el-form-item label="收货人姓名" prop="consigneeName">
            <el-input size="mini" v-model={this.formData.consigneeName} />
          </el-form-item>
          <el-form-item label="手机号码" prop="consigneeMobile">
            <el-input size="mini" v-model={this.formData.consigneeMobile} />
          </el-form-item>
          <el-form-item
            label="固定电话"
            class="fixed-telephone"
            prop="fixedTelephone"
          >
            <el-input
              size="mini"
              v-model={this.formData.telephoneAreaCode}
              maxlength="4"
            />
            <span>-</span>
            <el-input
              size="mini"
              v-model={this.formData.consigneeTelephone}
              maxlength="8"
            />
          </el-form-item>
          <el-form-item>
            <el-checkbox
              v-show={!this.hideDefaultStatus}
              v-model={this.formData.defaultStatus}
            >
              设置为默认收货地址
            </el-checkbox>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button
            size="mini"
            onClick={() => this.$emit('update:show', false)}
            disabled={this.loading}
          >
            取 消
          </el-button>
          <el-button
            size="mini"
            type="primary"
            onClick={this.save}
            loading={this.loading}
          >
            保 存
          </el-button>
        </span>
      </el-dialog>
    )
  }

  private save() {
    const form = this.$refs.form as ElForm
    this.loading = true

    form.validate(result => {
      let url = '/seal/rest/account/insertDeliveryAddress'

      if ('id' in this.formData) {
        url = '/seal/rest/account/modifyDeliveryAddress'
      }

      if (result) {
        service({
          url,
          method: 'POST',
          body: {
            ...this.formData,
            defaultStatus: this.formData.defaultStatus ? 1 : 0,
          },
        })
          .then(res => {
            this.$emit('update:show', false)
            this.$emit('success', this.formData)
            this.loading = false
          })
          .catch(err => {
            this.loading = false
            this.$emit('error', err)
          })
      } else {
        this.loading = false
      }
    })
  }

  @Watch('formData.telephoneAreaCode')
  private telephoneAreaCodeWatch(val: string) {
    this.formData.fixedTelephone = `${val}-${this.formData.consigneeTelephone}`
  }

  @Watch('formData.consigneeTelephone')
  private consigneeTelephoneCodeWatch(val: string) {
    this.formData.fixedTelephone = `${this.formData.telephoneAreaCode}-${val}`
  }

  @Watch('show')
  private showWatch(val: any) {
    if (val) {
      if ('id' in this.syncData) {
        const [province, city, area] = this.syncData.fullCode.split('-')

        this.title = '修改收货地址'
        this.hideDefaultStatus = Boolean(this.syncData.defaultStatus)

        this.formData = Object.assign({}, this.formData, {
          ...this.syncData,
          consigneeArea: this.syncData.fullCode,
          defaultStatus: this.hideDefaultStatus,
        })
        this.addressData = {
          province,
          city,
          area,
        }
      } else {
        this.hideDefaultStatus = false
        this.title = '新增收货地址'
      }
    } else {
      this.formData = {
        consigneeArea: '', // 用于判断地址是否填写
        cityName: '',
        areaName: '',
        provinceName: '',
        fullCode: '',
        areaDetail: '',
        postcode: '',
        consigneeName: '',
        consigneeMobile: '',
        telephoneAreaCode: '',
        consigneeTelephone: '',
        fixedTelephone: '', // 用于判断固定电话是否正确
        defaultStatus: false,
      }
      this.addressData = {
        province: '',
        city: '',
        area: '',
      }
      this.$emit('update:data', {})
      this.$nextTick(() => {
        // 清空验证信息
        const form = this.$refs.form as ElForm
        form && form.clearValidate()
      })
    }
  }
}
